from django.shortcuts import render,redirect
from django.http import JsonResponse,HttpResponseRedirect
from hashlib import sha1
from .models import *
from goods.models import GoodsInfo
from cart.models import CartInfo
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login as auth_login
from .models import UserInfo
# Create your views here.


def login(request):
    if request.method == 'POST':
        number = request.POST.get('number')
        password = request.POST.get('password')

        try:
            user_instance = UserInfo.objects.get(number=number)
            username = user_instance.username
            user = authenticate(request, username=username, password=password)
            if user is not None:
                auth_login(request, user)
                request.session['username'] = username  # 将用户名存储在会话中‘
                #request.session['number'] = number
                return redirect('/')
            else:
                context = {'error_msg': '密码错误'}
                return render(request, 'user/login.html', context)
        except UserInfo.DoesNotExist:
            context = {'error_msg': '学号不存在'}
            return render(request, 'user/login.html', context)
    else:
        return render(request, 'user/login.html')

def login_handle(request):
    post = request.POST
    number = post.get('number')
    password = post.get('password')
    users = UserInfo.objects.filter(number=number)
    print(number)
    if len(users) == 1:
        s1 = sha1()
        s1.update(password.encode('utf8'))
        if s1.hexdigest() == users[0].password:
            red = HttpResponseRedirect('/')
            request.session['user_id'] = users[0].id
            request.session['number'] = number
            request.session['username'] = users[0].username
            return red
        else:
            context = {'title': '用户登录', 'number': number, 'password': password, 'error_msg':'密码错误'}
            return render(request, 'user/login.html', context)
    else:
        context = {'title': '用户登录',  'number': number, 'password': password, 'error_msg':'学号错误'}

        return render(request, 'user/login.html', context)


from django.contrib.auth import logout as auth_logout

def logout(request):
    auth_logout(request)
    return redirect('/')

def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        number = request.POST.get('number')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')

        if password != password2:
            context = {'error_msg': '两次输入的密码不一致'}
            return render(request, 'user/register.html', context)

        if UserInfo.objects.filter(username=username).exists():
            context = {'error_msg': '用户名已存在'}
            return render(request, 'user/register.html', context)

        if UserInfo.objects.filter(number=number).exists():
            context = {'error_msg': '学号已存在'}
            return render(request, 'user/register.html', context)

        user = UserInfo.objects.create_user(username=username, password=password, number=number)
        user.save()
        return redirect('user:login')
    else:
        return render(request, 'user/register.html')

def register_handle(request):
    post = request.POST
    username = post.get('username')
    password = post.get('password')
    password2 = post.get('password2')
    number = post.get('number')
    if password != password2:
        return redirect('/user/register/')
    s1 = sha1()
    s1.update(password.encode('utf8'))
    upwd3 = s1.hexdigest()
    user = UserInfo()
    user.username = username
    user.password = upwd3
    user.number = number
    user.save()
    return redirect('/user/login')

from django.contrib.auth.decorators import login_required

@login_required(login_url='user:login')
def user_center(request):
    user = request.user
    return render(request, 'user/user_center.html', {'user': user})

def reset_password(request):
    context = {}
    return render(request,'user/reset_password.html',context)

def release_records(request):
    context = {}
    return render(request,'user/release_records.html',context)

def purchase_record(request):
    context = {}
    return render(request,'user/purchase_record.html',context)

def collection(request):
    context = {}
    return render(request,'user/collection.html',context)

def browse_history(request):
    context = {}
    return render(request,'user/browse_history.html',context)

def c_password(request):
    context = {}
    return render(request,'user/c_password.html',context)

def logon_record(request):
    context = {}
    return render(request,'user/logon_record.html',context)

def cart(request):
    username = request.session.get('username')
    if username == None:
        context = {'error_msg': '请先登录'}
        return render(request, 'user/login.html', context)
    else:
        title = request.GET['title']
        good = GoodsInfo.goods.get_title(title)[0]
        user = UserInfo.objects.filter(username=username)[0]
        cart = CartInfo.objects.create(title=good.title,type=good.type,picture=good.picture,price=good.price,buyer=user, good=good)
        cart.save()
        carts = CartInfo.objects.filter(buyer=user)
        total_price = 0
        total = 0
        for c in carts:
            total = total + 1
            total_price = total_price +c.price
        context = {'carts': carts, 'total_price':total_price, 'total':total}
        return render(request,'user/cart.html',context)


def delete_cart(request):
    title = request.GET['title']
    cart = CartInfo.objects.filter(title=title)[0]
    print(cart)
    cart.delete()
    username = request.session.get('username')
    user = UserInfo.objects.filter(username=username)[0]
    carts = CartInfo.objects.filter(buyer=user)
    total_price = 0
    total = 0
    for c in carts:
        total = total + 1
        total_price = total_price + c.price
    context = {'carts': carts, 'total_price': total_price, 'total': total}
    return render(request, 'user/cart.html', context)

# user/views.py
from django.shortcuts import render, get_object_or_404
from .models import UserInfo

def profile(request, user_id):
    user = get_object_or_404(UserInfo, id=user_id)
    return render(request, 'user/profile.html', {'user': user})



from chat.models import ChatRoom

# @login_required
# def selling_goods(request):
#     user = request.user
#     chatrooms = ChatRoom.objects.filter(participants=user, good__isDelete=False)
#     return render(request, 'user/selling_goods.html', {'chatrooms': chatrooms})



# @login_required
# def buying_goods(request):
#     user = request.user
#     chatrooms = ChatRoom.objects.filter(participants=user, good__isDelete=False)
#     return render(request, 'user/buying_goods.html', {'chatrooms': chatrooms})

@login_required
def selling_goods(request):
    user = request.user
    chatrooms = ChatRoom.objects.filter(participants=user, good__isDelete=False)
    selling_chatrooms = []

    for chatroom in chatrooms:
        room_name_parts = chatroom.name.split('_')
        if len(room_name_parts) == 3 and room_name_parts[1] == str(user.id):
            selling_chatrooms.append(chatroom)

    return render(request, 'user/selling_goods.html', {'chatrooms': selling_chatrooms})

@login_required
def buying_goods(request):
    user = request.user
    chatrooms = ChatRoom.objects.filter(participants=user, good__isDelete=False)
    buying_chatrooms = []

    for chatroom in chatrooms:
        room_name_parts = chatroom.name.split('_')
        if len(room_name_parts) == 3 and room_name_parts[0] == str(user.id):
            buying_chatrooms.append(chatroom)

    return render(request, 'user/buying_goods.html', {'chatrooms': buying_chatrooms})

from django.core.paginator import Paginator
@login_required
def release_records(request):
    user_id = request.session.get('_auth_user_id')
    user = UserInfo.objects.get(id=user_id)
    goods_list = GoodsInfo.objects.filter(user=user).order_by('-created_at')
    
    # 分页
    paginator = Paginator(goods_list, 10)  # 每页显示10个物品
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {'page_obj': page_obj}
    return render(request, 'user/release_records.html', context)

@login_required
def delete_good(request, good_id):
    good = get_object_or_404(GoodsInfo, id=good_id)
    good.delete()
    return redirect('user:release_records')


from django.contrib import messages
@login_required
def edit_profile(request):
    user = request.user
    if request.method == 'POST':
        phone = request.POST.get('phone')
        email = request.POST.get('email')
        description = request.POST.get('description')
        
        user.phone = phone
        user.email = email
        user.description = description
        user.save()
        
        messages.success(request, '个人信息更新成功')
        return redirect('user:user_center')
    
    return render(request, 'user/edit_profile.html', {'user': user})